package org.jeecg.modules.lab.entrust.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.device.vo.LabDevicePage;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItems;
import org.jeecg.modules.lab.entrust.entity.LabWscientific;
import org.jeecg.modules.lab.entrust.service.ILabEntrustItemsService;
import org.jeecg.modules.lab.entrust.service.ILabWscientificService;
import org.jeecg.modules.lab.entrust.vo.LabWscientificItemPage;
import org.jeecg.modules.lab.entrust.vo.LabWscientificPage;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.jeecg.modules.lab.items.record.service.*;
import org.jeecg.modules.lab.items.vo.LabItemRecordKy;
import org.jeecg.modules.lab.items.vo.LabItemRecordPage;
import org.jeecg.modules.lab.util.ImportExportUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 科研项目
 * @Author: jeecg-boot
 * @Date: 2023-11-17
 * @Version: V1.0
 */
@Api(tags = "科研项目")
@RestController
@RequestMapping("/entrust/labWscientific")
@Slf4j
public class LabWscientificController extends JeecgController<LabWscientific, ILabWscientificService> {
    @Autowired
    private ILabWscientificService labWscientificService;

    @Autowired
    private ILabItemsService labItemsService;

    @Autowired
    private ILabEntrustItemsService labEntrustItemsService;

    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;
    //原始记录仪器
    @Autowired
    private ILabItemsRecordDeviceService labItemsRecordDeviceService;
    //原始记录内容
    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;
    //原始记录结果
    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;
    //原始记录检测人
    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;
    @Autowired
    private ILabCronJobService labCronJobService;

    @Autowired
    private LabWentrustController labWentrustController;

    /**
     * 分页列表查询
     *
     * @param labWscientific
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "科研项目-分页列表查询")
    @ApiOperation(value = "科研项目-分页列表查询", notes = "科研项目-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabWscientific>> queryPageList(LabWscientific labWscientific,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<LabWscientific> queryWrapper = new QueryWrapper<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userTId = loginUser.getTId();
        String userName = loginUser.getUsername();
        String userId = loginUser.getId();
        if (labWscientific.getPlanTitle() != null) {
            String entName = labWscientific.getPlanTitle();
            String replace = entName.replace("*", "");
            queryWrapper.like("plan_title", "%" + replace + "%");
        }
        if (labWscientific.getKyDate() != null) {
            Date createTime = labWscientific.getKyDate();
            queryWrapper.eq("ky_date", createTime);
        }
        Page<LabWscientific> page = new Page<LabWscientific>(pageNo, pageSize);
        IPage<LabWscientific> pageList = labWscientificService.page(page, queryWrapper);
        ArrayList<LabWscientific> labWscientifics = new ArrayList<>();
        if (userName.contains("admin")) {
            labWscientifics.addAll(pageList.getRecords());
        } else {
            if (userTId != null && !"".equals(userTId)) {
                for (LabWscientific record : pageList.getRecords()) {
                    if (record.getPlanUsersId().contains(userTId)) {
                        labWscientifics.add(record);
                    } else {
                        QueryWrapper<LabEntrustItems> objectQueryWrapper = new QueryWrapper<>();
                        objectQueryWrapper.eq("entrust_id", record.getId());
                        List<LabEntrustItems> list = labEntrustItemsService.list(objectQueryWrapper);
                        for (LabEntrustItems labEntrustItems : list) {
                            if (labEntrustItems.getUserId().contains(userId)) {
                                labWscientifics.add(record);
                                break;
                            }
                        }
                    }
                }
            }
        }

        Page pageA = new Page();
        pageA.setRecords(labWscientifics);
        pageA.setTotal(labWscientifics.size());
        pageA.setSize(pageSize);
        pageA.setCurrent(pageNo);
        return Result.OK(pageA);
    }

    /**
     * 分页列表查询
     *
     * @param labWscientific
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "科研项目-分页列表查询")
    @ApiOperation(value = "科研项目-分页列表查询", notes = "科研项目-分页列表查询")
    @GetMapping(value = "/list2")
    public Result<IPage<LabEntrustItems>> queryPageList2(LabWscientific labWscientific,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<LabEntrustItems> queryWrapper = new QueryWrapper<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String tId = loginUser.getTId();
        String userId = loginUser.getId();
        if (tId != null && !tId.equals(labWscientific.getKyManagerId())) {
            queryWrapper.like("user_id", "%" + userId + "%");
        }
        queryWrapper.eq("entrust_id", labWscientific.getId());
        Page<LabEntrustItems> page = new Page<LabEntrustItems>(pageNo, pageSize);
        IPage<LabEntrustItems> pageList = labEntrustItemsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param labWscientific
     * @return
     */
    @AutoLog(value = "科研项目-添加")
    @ApiOperation(value = "科研项目-添加", notes = "科研项目-添加")
//    @RequiresPermissions("scientific:lab_wscientific:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabWscientific labWscientific) {
        labWscientificService.save(labWscientific);
        if (MyEnum.sync) {
            long time = new Date().getTime();
            LabCronJob job = new LabCronJob("lab_wscientific", "0", time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labWscientific
     * @return
     */
    @AutoLog(value = "科研项目-编辑")
    @ApiOperation(value = "科研项目-编辑", notes = "科研项目-编辑")
//    @RequiresPermissions("scientific:lab_wscientific:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabWscientific labWscientific) {
        labWscientific.setSynFlag("1");
        labWscientificService.updateById(labWscientific);
        if (MyEnum.sync) {
            long time = new Date().getTime();
            LabCronJob job = new LabCronJob("lab_wscientific", "1", time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "科研项目-通过id删除")
    @ApiOperation(value = "科研项目-通过id删除", notes = "科研项目-通过id删除")
//    @RequiresPermissions("scientific:lab_wscientific:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        labWscientificService.removeById(id);
        if (MyEnum.sync) {
            long time = new Date().getTime();
            String condition = "id='" + id + "'";
            LabCronJob job = new LabCronJob("lab_wscientific", "2", condition, time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "科研项目-批量删除")
    @ApiOperation(value = "科研项目-批量删除", notes = "科研项目-批量删除")
//    @RequiresPermissions("scientific:lab_wscientific:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labWscientificService.removeByIds(Arrays.asList(ids.split(",")));
        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            labCronJobService.saveCronBatch("lab_wscientific", "2", time, idList);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "科研项目-通过id查询")
    @ApiOperation(value = "科研项目-通过id查询", notes = "科研项目-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabWscientific> queryById(@RequestParam(name = "id", required = true) String id) {
        LabWscientific labWscientific = labWscientificService.getById(id);
        if (labWscientific == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labWscientific);
    }

    /**
     * 通过id查询
     *
     * @return
     */
    @ApiOperation(value = "科研项目-同步科研项目数据", notes = "科研项目-同步科研项目数据")
    @GetMapping(value = "/syncKyProject")
    public Result<String> syncKyProject() throws MalformedURLException {
        String kyStr = "";
        labWscientificService.syncKyProject(kyStr);

        if (MyEnum.sync) {
            //同步表信息
            long time = new Date().getTime();
            ArrayList<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_wscientific", "1", time, 1));
            jobs.add(new LabCronJob("lab_wscientific", "0", time, 2));
            labCronJobService.saveBatch(jobs);
        }
        return Result.OK("同步科研项目成功!");
    }


    /**
     * 根据检测项目查询记录数据
     *
     * @return
     */
    @ApiOperation(value = "科研项目-根据科研项目id查询记录数据", notes = "科研项目-根据科研项目id查询记录数据")
    @GetMapping(value = "/getItemRecordData")
    public Result<List<LabItemRecordPage>> getItemRecordData(@RequestParam(name = "ky_id", required = true) String ky_id) {

        List<LabItemRecordPage> labItemRecordPageList = new ArrayList<>();
        QueryWrapper<LabWscientific> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ky_id", ky_id);
        LabWscientific labWscientific = labWscientificService.getOne(queryWrapper);

        if (labWscientific == null) {
            return Result.OK(labItemRecordPageList);
        }
        String entrust_id = labWscientific.getId();
        QueryWrapper<LabEntrustItems> wrapper = new QueryWrapper<>();
        wrapper.eq("entrust_id", entrust_id).orderByAsc("create_time");
        List<LabEntrustItems> labEntrustItemsList = labEntrustItemsService.list(wrapper);

        if (labEntrustItemsList.size() > 0) {
            for (LabEntrustItems item : labEntrustItemsList) {
                // 执行操作
                String taskItemId = item.getId();
                String itemId = item.getItemId();
                String entrustId = item.getEntrustId();
                LabItemRecordPage labItemRecordPage = new LabItemRecordPage();
                labItemRecordPage.setItemName(item.getItemName());
                labItemRecordPage.setSamName(item.getSamName());
                labItemRecordPage.setBasisName(item.getBasisName());
                labItemRecordPage.setBasisNum(item.getBasisNum());
                labItemRecordPage.setUserName(item.getUserName());
                labItemRecordPage.setItemStartTime(String.valueOf(item.getItemStartTime()));
                labItemRecordPage.setItemFinishTime(String.valueOf(item.getItemFinishTime()));
                labItemRecordPage.setLabRecordSamList(labItemsRecordSampleService.handleSamData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordDevList(labItemsRecordDeviceService.handleDevData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordNormList(labItemsRecordNormService.handleNormData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordTargList(labItemsRecordTargetService.handleTargData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordPerList(labItemsRecordPersonService.handlePerData(entrustId, taskItemId, itemId));
                labItemRecordPageList.add(labItemRecordPage);
            }
            return Result.OK(labItemRecordPageList);
        } else {
            return Result.OK(labItemRecordPageList);
        }

    }


    /**
     * 根据检测项目查询记录数据
     *
     * @return
     */
    @ApiOperation(value = "科研项目-根据实验方案id查询记录数据", notes = "科研项目-根据实验方案id查询记录数据")
    @GetMapping(value = "/getItemRecordDataB")
    public Result<LabItemRecordKy> getItemRecordDataB(@RequestParam(name = "sy_id", required = true) String sy_id) {

        LabItemRecordKy labItemRecordKy = new LabItemRecordKy();
        List<LabItemRecordPage> labItemRecordPageList = new ArrayList<>();
        QueryWrapper<LabWscientific> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_id", sy_id);
        LabWscientific labWscientific = labWscientificService.getOne(queryWrapper);

        if (labWscientific == null) {
            return Result.OK(labItemRecordKy);
        }
        String entrust_id = labWscientific.getId();
        QueryWrapper<LabEntrustItems> wrapper = new QueryWrapper<>();
        wrapper.eq("entrust_id", entrust_id).orderByAsc("create_time");
        List<LabEntrustItems> labEntrustItemsList = labEntrustItemsService.list(wrapper);
        labItemRecordKy.setSyNum(labEntrustItemsList.size());
        ;
        if (labEntrustItemsList.size() > 0) {
            for (LabEntrustItems item : labEntrustItemsList) {
                // 执行操作
                String taskItemId = item.getId();
                String itemId = item.getItemId();
                String entrustId = item.getEntrustId();
                LabItemRecordPage labItemRecordPage = new LabItemRecordPage();
                labItemRecordPage.setItemName(item.getItemName());
                labItemRecordPage.setSamName(item.getSamName());
                labItemRecordPage.setBasisName(item.getBasisName());
                labItemRecordPage.setBasisNum(item.getBasisNum());
                labItemRecordPage.setUserName(item.getUserName());
                labItemRecordPage.setItemStartTime(String.valueOf(item.getItemStartTime()));
                labItemRecordPage.setItemFinishTime(String.valueOf(item.getItemFinishTime()));
                labItemRecordPage.setLabRecordSamList(labItemsRecordSampleService.handleSamData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordDevList(labItemsRecordDeviceService.handleDevData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordNormList(labItemsRecordNormService.handleNormData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordTargList(labItemsRecordTargetService.handleTargData(entrustId, taskItemId, itemId));
                labItemRecordPage.setLabRecordPerList(labItemsRecordPersonService.handlePerData(entrustId, taskItemId, itemId));
                labItemRecordPageList.add(labItemRecordPage);
            }
            labItemRecordKy.setLabItemRecordPageList(labItemRecordPageList);
            return Result.OK(labItemRecordKy);
        } else {
            return Result.OK(labItemRecordKy);
        }

    }

    /**
     * 科研项目-原始记录本
     *
     * @param year
     * @param kyId
     * @param planId
     * @return
     */
    @ApiOperation(value = "科研项目-原始记录本", notes = "科研项目-原始记录本")
    @GetMapping(value = "/getLabWKyCount")
    public Result<List<LabWscientificPage>> getLabWKyCount(@RequestParam(name = "year", defaultValue = "") String year,
                                                           @RequestParam(name = "kyId", defaultValue = "") String kyId,
                                                           @RequestParam(name = "planId", defaultValue = "") String planId) {
        List<LabWscientificPage> wscientificPageList = labWscientificService.getWKyCount(year, kyId, planId);
        return Result.OK(wscientificPageList);
    }

    /**
     * 科研项目-结果分析
     *
     * @param year
     * @param kyId
     * @param planId
     * @return
     */
    @ApiOperation(value = "科研项目-结果分析", notes = "科研项目-结果分析")
    @GetMapping(value = "/getLabWKyAnalysis")
    public Result<List<LabWscientificItemPage>> getLabWKyAnalysis(@RequestParam(name = "year", defaultValue = "") String year,
                                                                  @RequestParam(name = "kyId", defaultValue = "") String kyId,
                                                                  @RequestParam(name = "planId", defaultValue = "") String planId) {
        List<LabWscientificItemPage> wscientificItemPageList = labWscientificService.getLabWKyAnalysis(year, kyId, planId);
        return Result.OK(wscientificItemPageList);
    }


    /**
     * 科研项目-导出excel结果分析
     */
    @RequestMapping(value = "/exportXlsWKyAnalysis")
    public ModelAndView exportXlsWKyAnalysis(@RequestParam(name = "year", defaultValue = "") String year,
                                             @RequestParam(name = "kyId", defaultValue = "") String kyId,
                                             @RequestParam(name = "planId", defaultValue = "") String planId) {

        List<LabWscientificItemPage> wscientificItemPageList = labWscientificService.getLabWKyAnalysis(year, kyId, planId);
        ImportExportUtil exportUtil = new ImportExportUtil();
        return exportUtil.exportXlsBySql(wscientificItemPageList, LabWscientificItemPage.class, "实验数据分析");
    }


    /**
     * 导出excel
     *
     * @param request
     * @param labWscientific
     */
    @RequiresPermissions("scientific:lab_wscientific:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabWscientific labWscientific) {
        return super.exportXls(request, labWscientific, LabWscientific.class, "科研项目");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("scientific:lab_wscientific:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabWscientific.class);
    }

    /**
     * 查询有模板的检测项目
     *
     * @return
     */
    @ApiOperation(value = "查询有模板的检测项目", notes = "查询有模板的检测项目")
    @GetMapping(value = "/queryTemd")
    public Result<List> queryTemd(@RequestParam(name = "nameswa", required = false) String nameswa) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        List<LabItems> labItemsList = labItemsService.getItemsTempList(nameswa, userId);
        List<LabItems> itemsListA = new ArrayList<>();
        for (LabItems item : labItemsList) {
            String name = item.getName();
            boolean bool = true;
            for (LabItems itemA : itemsListA) {
                String nameA = itemA.getName();
                if (name.equals(nameA)) {
                    bool = false;
                }
            }
            if (bool) {
                itemsListA.add(item);
            }
        }
        return Result.OK(itemsListA);
    }

    /**
     * @param kyId
     * @param response
     * @throws ParseException
     * @throws IOException
     * @throws IllegalAccessException
     * @throws TemplateException
     */
    @ApiOperation(value = "科研项目-下载原始记", notes = "科研项目-下载原始记")
    @PostMapping(value = "/downloadShiYanAsZip/{kyId}")
    public ResponseEntity<Resource> downloadShiYanAsZip(@PathVariable(name = "kyId", required = false) String kyId, HttpServletResponse response) throws ParseException, IOException, IllegalAccessException, TemplateException {

        String fileName = "";
        // todo 先查询科研数据
        QueryWrapper<LabWscientific> queryWrappera = new QueryWrapper<>();
        queryWrappera.eq("ky_id", kyId);
        List<LabWscientific> wscientificList = labWscientificService.list(queryWrappera);
        if (wscientificList == null && wscientificList.size() == 0) {
            throw new RuntimeException("未找到对应数据!");
        }
        List<String> ids = new ArrayList<>();
        for (LabWscientific wsc : wscientificList) {
            ids.add(wsc.getId());
            if ("".equals(fileName)) {
                fileName = wsc.getKyName();
            }
        }

        QueryWrapper<LabEntrustItems> queryWrapperb = new QueryWrapper<>();
        queryWrapperb.in("entrust_id", ids);
        List<LabEntrustItems> items = labEntrustItemsService.list(queryWrapperb);
        if (items != null) {
            String folderPatha = "D:\\zhuiExperiment\\template";
            String folderPathb = "D:\\zhuiExperiment\\download\\" + fileName;
            File file = new File(folderPathb);
            if (!file.exists()) {
                file.mkdir();
            }
            for (int i = 0; i < items.size(); i++) {
                LabEntrustItems item = items.get(i);
                String itemName = item.getItemName();
                if (item.getItemName().contains("/")) {
                    itemName = item.getItemName().replace("/", "-");
                }
                String task_item_id = item.getId();
                Map mapData = labWentrustController.ronrew(itemName, task_item_id);

                Map itemData = (Map) mapData.get("data");
                replaceNull(itemData);
                String itmePath = itemName + ".xml";
                String fileUrl = folderPathb +"\\"+ itemName;
                File fileA = new File(fileUrl);
                if (!fileA.exists()) {
                    fileA.mkdir();
                }
                parse(folderPatha, itmePath, fileUrl + "\\" + itemName + "_" + (i + 1) + ".docx", itemData);
            }
            // 压缩文件
            zipFolder(folderPathb);
            // 下载文件
            try {
                File fileB = new File(folderPathb + ".zip");
                ResponseEntity<Resource> resourceResponseEntity = getResourceResponseEntity(fileB, fileName + ".zip");
                fileB.delete();
                return resourceResponseEntity;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }


    @NotNull
    public static ResponseEntity<Resource> getResourceResponseEntity(File tempFile, String fileName) throws IOException {
        // 加载临时文件作为资源
        Resource fileResource = new FileSystemResource(tempFile);
        // 设置响应头
        HttpHeaders headersQuery = new HttpHeaders();
        headersQuery.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        // 创建ResponseEntity，包含文件资源和响应头
        return ResponseEntity
                .ok()
                .headers(headersQuery)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(new InputStreamResource(fileResource.getInputStream()));
    }

    public void replaceNull(Map data) {
        Set keys = data.keySet();
        for (Object key : keys) {
            if (data.get(key) == null) {
                data.put(key, "");
            }
        }
    }

    public void parse(String templateDir, String templateName, String excelPath, Map<String, Object> data) throws IOException, freemarker.template.TemplateException {
        //初始化工作
        Configuration cfg = new Configuration();
        //设置默认编码格式为UTF-8
        cfg.setDefaultEncoding("gbk");
        //全局数字格式
        cfg.setNumberFormat("0");
        //设置模板文件位置
        cfg.setDirectoryForTemplateLoading(new File(templateDir));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        //加载模板
        freemarker.template.Template template = cfg.getTemplate(templateName, "utf-8");
        Writer writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(excelPath), "UTF-8"));
            template.process(data, writer);

            writer.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 通过 HTTP 响应下载 ZIP 文件
     *
     * @param sourceDir 要下载的文件夹路径
     */
    public static void zipFolder(String sourceDir) throws IOException {
        String zipFilePath = sourceDir + ".zip";
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            Path sourcePath = Paths.get(sourceDir);
            Files.walk(sourcePath)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        String relativePath = sourcePath.relativize(path).toString();
                        addToZip(zos, path.toFile(), relativePath);
                    });
        }
    }


    private static void addToZip(ZipOutputStream zos, File file, String entryName) {
        try (FileInputStream fis = new FileInputStream(file)) {
            // 替换Windows路径分隔符为ZIP标准分隔符
            ZipEntry zipEntry = new ZipEntry(entryName.replace(File.separator, "/"));
            zos.putNextEntry(zipEntry);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
        } catch (IOException e) {
            System.err.println("Error adding file: " + file.getAbsolutePath());
            e.printStackTrace();
        }
    }


}
